package pers.sloera.leetcode.editor.cn;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 实现一个魔法字典
 *
 * @author sloera
 * @date 2022-07-11 23:11:38
 */
class ImplementMagicDictionary {
  public static void main(String[] args) {
    ImplementMagicDictionary implementMagicDictionary = new ImplementMagicDictionary();
  }

  // leetcode submit region begin(Prohibit modification and deletion)
  class MagicDictionary {
    Set<String> dictionarySet;
    // ArrayList<Pattern> patterns = new ArrayList<>();
    HashMap<String, List<Pattern>> dictPatternMap = new HashMap<>();

    public MagicDictionary() {}

    public void buildDict(String[] dictionary) {
      dictionarySet = Arrays.stream(dictionary).collect(Collectors.toSet());
      Arrays.stream(dictionary)
          .forEach(
              dict -> {
                char[] chars = dict.toCharArray();
                List<Pattern> patterns = new ArrayList<>();
                for (int i = 0; i < chars.length; i++) {
                  String left = "";
                  if (i > 0) {
                    left = dict.substring(0, i);
                  }
                  String right = "";
                  if (i + 1 < dict.length()) {
                    right = dict.substring(i + 1);
                  }
                  patterns.add(Pattern.compile("^" + left + "[^" + chars[i] + "]" + right + "$"));
                }
                dictPatternMap.put(dict, patterns);
              });
    }

    public boolean search(String searchWord) {
      return dictPatternMap.entrySet().stream()
          .filter(
              dictPattern ->
                  !dictPattern.getKey().equals(searchWord)
                      && dictPattern.getKey().length() == searchWord.length())
          .map(Map.Entry::getValue)
          .anyMatch(
              patterns ->
                  patterns.stream().anyMatch(pattern -> pattern.matcher(searchWord).find()));
    }
  }

  /**
   * Your MagicDictionary object will be instantiated and called as such: MagicDictionary obj = new
   * MagicDictionary(); obj.buildDict(dictionary); boolean param_2 = obj.search(searchWord);
   */
  // leetcode submit region end(Prohibit modification and deletion)

}
